package com.yfuxdeer.youchat.utils;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import com.yfuxdeer.youchat.service.FriendService;
import com.yfuxdeer.youchat.R;
import com.yfuxdeer.youchat.pojo.Message;

public class NotificationUtil {
    public static void sendNotification(Context context, Class targetClass, Message message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                createNotificationChannel(context, "message", "消息", NotificationManager.IMPORTANCE_HIGH);
                Intent intent = new Intent(context, targetClass);
                intent.putExtra("friend_id", message.getFrom());
                PendingIntent pendingIntent = PendingIntent.getActivity(context, R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "message");
                try {
                    builder.setContentIntent(pendingIntent)
                            .setAutoCancel(true)
                            .setSmallIcon(R.drawable.default_head)
                            .setTicker("提示消息").setWhen(System.currentTimeMillis())
                            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.bottom3))
                            .setContentTitle(FriendService.findFriendById(message.getTo(), message.getFrom()).getRemark())
                            .setContentText(message.getMsg());
                } catch (Exception e) {
                    Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
                }
                Notification notification = builder.build();
                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(1, notification);
            }
        }).start();
    }

    private static void createNotificationChannel(Context context, String channelId, String channelName, int importance) {
        NotificationChannel notificationChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel(channelId, channelName, importance);
        }
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationManager.createNotificationChannel(notificationChannel);
        }
    }
}
